#!/bin/bash

echo "========================================"
echo "    RocketMQ项目一键部署脚本"
echo "========================================"
echo

# 设置变量
SERVER_IP="192.168.211.139"
SERVER_USER="root"
SSH_KEY="C:/Users/Teriberka/.ssh/my_linux_key"
PROJECT_NAME="rocketmq-rate-limit-demo"

echo "服务器信息:"
echo "- IP地址: $SERVER_IP"
echo "- 用户名: $SERVER_USER"
echo "- SSH密钥: $SSH_KEY"
echo

# 检查Maven是否安装
echo "检查环境..."
if ! command -v mvn &> /dev/null; then
    echo "✗ Maven未安装或不在PATH中"
    exit 1
fi
echo "✓ Maven已安装"
echo

# 清理旧的构建文件
echo "1. 清理旧的构建文件..."
rm -f target/*.jar
echo "✓ 清理完成"
echo

# Maven构建项目
echo "2. Maven构建项目..."
mvn clean package -DskipTests
if [ $? -ne 0 ]; then
    echo "✗ Maven构建失败"
    exit 1
fi
echo "✓ Maven构建成功"
echo

# 检查jar包是否存在
JAR_FILE=$(find target -name "${PROJECT_NAME}-*.jar" | head -n 1)
if [ -z "$JAR_FILE" ]; then
    echo "✗ 未找到构建的jar包"
    exit 1
fi
echo "找到jar包: $JAR_FILE"
echo

# 创建临时部署目录
echo "3. 准备部署文件..."
rm -rf deploy
mkdir -p deploy
cp "$JAR_FILE" deploy/app.jar
cp Dockerfile deploy/
cp broker.conf deploy/
echo "✓ 部署文件准备完成"
echo

# 上传文件到服务器
echo "4. 上传文件到服务器..."
scp -i "$SSH_KEY" -r deploy/* "${SERVER_USER}@${SERVER_IP}:/home/rocketmq/"
if [ $? -ne 0 ]; then
    echo "✗ 文件上传失败"
    exit 1
fi
echo "✓ 文件上传成功"
echo

# 在服务器上构建和部署
echo "5. 在服务器上构建和部署..."
ssh -i "$SSH_KEY" "${SERVER_USER}@${SERVER_IP}" << 'EOF'
cd /home/rocketmq

echo "停止现有容器..."
docker stop rocketmq-app 2>/dev/null || true
docker rm rocketmq-app 2>/dev/null || true

echo "删除旧镜像..."
docker rmi rocketmq-app:latest 2>/dev/null || true

echo "构建新镜像..."
docker build -t rocketmq-app:latest .

if [ $? -eq 0 ]; then
    echo "镜像构建成功，启动应用容器..."
    docker run -d \
      --name rocketmq-app \
      --network rmq \
      -p 8080:8080 \
      -e SPRING_PROFILES_ACTIVE=prod \
      -e ROCKETMQ_NAMESRV_ADDR=192.168.211.139:9876 \
      -v /home/rocketmq/logs/app:/app/logs \
      --restart unless-stopped \
      rocketmq-app:latest

    echo "等待应用启动..."
    sleep 15

    echo "检查容器状态..."
    docker ps | grep rocketmq-app

    echo "检查应用日志..."
    docker logs rocketmq-app --tail 10

    echo "测试应用健康状态..."
    if curl -f http://localhost:8080/api/rocketmq/health >/dev/null 2>&1; then
        echo "✓ 应用健康检查通过！"
    else
        echo "⚠ 应用还未完全启动，请稍后检查"
    fi

    echo "清理临时文件..."
    rm -f app.jar Dockerfile broker.conf
else
    echo "✗ 镜像构建失败！"
    exit 1
fi
EOF

if [ $? -ne 0 ]; then
    echo "✗ 服务器部署失败"
    exit 1
fi
echo "✓ 服务器部署成功"
echo

# 清理本地临时文件
echo "6. 清理本地临时文件..."
rm -rf deploy
echo "✓ 清理完成"
echo

echo "========================================"
echo "           部署完成！"
echo "========================================"
echo
echo "应用访问地址: http://$SERVER_IP:8080"
echo "健康检查: http://$SERVER_IP:8080/api/rocketmq/health"
echo
echo "常用命令:"
echo "- 查看容器状态: docker ps"
echo "- 查看应用日志: docker logs rocketmq-app"
echo "- 重启应用: docker restart rocketmq-app"
echo "- 停止应用: docker stop rocketmq-app"
echo
